<?php
/**
 * MySQL PDO 操作类
 * User: lisgroup
 * Date: 2017/11/26
 * Time: 17:00
 */

namespace lisfw\DB;


class MysqlQuery implements DbInterface
{
    /**
     * 数据库连接
     * @var \Mysqli|null
     */
    private $conn = null;

    public function __construct($configKey = 'DB_CONFIG')
    {
        if (is_null($this->conn)) {
            $dbConfig = config($configKey);
            $this->conn = new \Mysqli($dbConfig['DB_HOST'], $dbConfig['DB_USER'], $dbConfig['DB_PASSWORD'],
                $dbConfig['DB_NAME'], $dbConfig['DB_PORT']);

            if ($this->conn->connect_errno) {
                printf("Connect failed: %s\n", $this->conn->connect_error);
                exit();
            }
            $this->conn->set_charset($dbConfig['DB_CHARSET']);
        }
    }

    /**
     * 查询方法
     * @param $sql
     * @return bool|\mysqli_result
     */
    public function query($sql)
    {
        return $this->conn->query($sql);
    }

    /**
     * 1. 获取二维数组多列结果
     * @param $sql
     * @return array
     */
    public function getAll($sql)
    {
        $result = $this->query($sql);
        $array = array();
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $array[] = $row;
            }
        }
        return $array;
    }

    /**
     * 2. 获取一列数据
     * @param $sql
     * @return array
     */
    public function getCol($sql)
    {
        $result = $this->query($sql);
        $array = array();

        if ($result) {
            while ($row = $result->fetch_row()) {
                $array[] = $row[0];
            }
        }
        return $array;
    }

    /**
     * 3. 获取一行数据
     * @param $sql
     * @return array
     */
    public function getRow($sql)
    {
        $result = $this->query($sql);
        return $result->fetch_assoc();
    }

    /**
     * 4. 获取单个数据
     * @param $sql
     * @return string
     */
    public function getOne($sql)
    {
        $result = $this->query($sql);
        $row = $result->fetch_row();

        $string = '';
        if ($row) {
            $string = $row[0];
        }

        return $string;
    }

    /**
     * 关闭数据库连接
     */
    public function close()
    {
        $this->conn->close();
    }

    // 待添加功能

    public function __destruct()
    {
        $this->close();
    }
}